#!/bin/bash

# 2FA Manager - 环境配置脚本（Linux/macOS）
# 用于快速设置开发环境

echo "🚀 2FA Manager - 环境配置向导"
echo "================================"
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 检查Node.js
echo "📦 检查依赖..."
if ! command -v node &> /dev/null; then
    echo -e "${RED}❌ Node.js未安装，请先安装Node.js 18+${NC}"
    exit 1
fi
echo -e "${GREEN}✅ Node.js: $(node -v)${NC}"

# 检查npm
if ! command -v npm &> /dev/null; then
    echo -e "${RED}❌ npm未安装${NC}"
    exit 1
fi
echo -e "${GREEN}✅ npm: $(npm -v)${NC}"
echo ""

# 生成密钥
echo "🔐 生成安全密钥..."
JWT_SECRET=$(node -e "console.log(require('crypto').randomBytes(32).toString('base64'))")
REFRESH_TOKEN_SECRET=$(node -e "console.log(require('crypto').randomBytes(32).toString('base64'))")
ENCRYPTION_KEY=$(node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")
echo -e "${GREEN}✅ 已生成安全密钥${NC}"
echo ""

# 创建后端.env文件
echo "📝 创建后端环境配置..."
if [ -f "backend/.env" ]; then
    echo -e "${YELLOW}⚠️  backend/.env 已存在${NC}"
    read -p "是否覆盖？(y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "跳过后端配置..."
    else
        create_backend_env
    fi
else
    create_backend_env
fi

function create_backend_env() {
    cat > backend/.env << EOF
# 2FA Manager Backend Environment Variables
NODE_ENV=development
PORT=5000
HOST=localhost
DATABASE_URL=file:./dev.db

# JWT配置
JWT_SECRET=${JWT_SECRET}
REFRESH_TOKEN_SECRET=${REFRESH_TOKEN_SECRET}
JWT_EXPIRES_IN=15m
REFRESH_TOKEN_EXPIRES_IN=7d

# 加密配置
ENCRYPTION_KEY=${ENCRYPTION_KEY}

# CORS配置
ALLOWED_ORIGINS=http://localhost:3000

# 日志配置
LOG_LEVEL=debug

# 安全配置
COOKIE_SECURE=false
COOKIE_SAME_SITE=strict

# 会话配置
SESSION_TIMEOUT=1800
MAX_LOGIN_ATTEMPTS=5
LOCK_DURATION=15

# 备份配置
BACKUP_DIR=backups
BACKUP_RETENTION_DAYS=7
EOF

    chmod 600 backend/.env
    echo -e "${GREEN}✅ 已创建 backend/.env${NC}"
}

# 创建前端.env文件
echo ""
echo "📝 创建前端环境配置..."
if [ -f "frontend/.env" ]; then
    echo -e "${YELLOW}⚠️  frontend/.env 已存在${NC}"
    read -p "是否覆盖？(y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "跳过前端配置..."
    else
        create_frontend_env
    fi
else
    create_frontend_env
fi

function create_frontend_env() {
    cat > frontend/.env << EOF
# 2FA Manager Frontend Environment Variables
VITE_API_BASE_URL=http://localhost:5000
VITE_APP_NAME=2FA管理系统
VITE_APP_VERSION=1.0.0
VITE_DEBUG_MODE=false
VITE_DEFAULT_THEME=auto
VITE_DEFAULT_LANGUAGE=zh-CN
VITE_SESSION_TIMEOUT=30
VITE_TOKEN_REFRESH_INTERVAL=10
EOF

    echo -e "${GREEN}✅ 已创建 frontend/.env${NC}"
}

# 安装依赖
echo ""
echo "📦 安装项目依赖..."
read -p "是否安装依赖？(y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "安装根目录依赖..."
    npm install
    
    echo "安装后端依赖..."
    cd backend && npm install && cd ..
    
    echo "安装前端依赖..."
    cd frontend && npm install && cd ..
    
    echo -e "${GREEN}✅ 依赖安装完成${NC}"
fi

# 初始化数据库
echo ""
echo "🗄️  初始化数据库..."
read -p "是否初始化数据库？(y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    cd backend
    npm run migrate
    cd ..
    echo -e "${GREEN}✅ 数据库初始化完成${NC}"
fi

# 创建管理员
echo ""
echo "👤 创建管理员账户..."
read -p "是否创建管理员？(y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    cd backend
    npm run create-admin
    cd ..
fi

# 完成
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "${GREEN}✨ 环境配置完成！${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📝 生成的密钥信息："
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "${BLUE}JWT_SECRET:${NC}"
echo "$JWT_SECRET"
echo ""
echo -e "${BLUE}REFRESH_TOKEN_SECRET:${NC}"
echo "$REFRESH_TOKEN_SECRET"
echo ""
echo -e "${BLUE}ENCRYPTION_KEY:${NC}"
echo "$ENCRYPTION_KEY"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "🚀 下一步："
echo "  1. cd backend && npm run dev    # 启动后端"
echo "  2. cd frontend && npm run dev   # 启动前端（新终端）"
echo ""
echo "或使用根目录命令："
echo "  npm run dev    # 同时启动前后端"
echo ""
echo "🌐 访问地址："
echo "  前端: http://localhost:3000"
echo "  后端: http://localhost:5000"
echo ""
echo -e "${YELLOW}⚠️  请妥善保管上述密钥，不要泄露！${NC}"
echo ""

